﻿using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace NetMonitor
{
    public partial class MainWindow : Window
    {
        // 性能计数器
        private PerformanceCounter downloadCounter;
        private PerformanceCounter uploadCounter;

        // 计时器
        private DispatcherTimer timer;

        // 网络适配器列表
        private List<string> networkAdapters = new List<string>();
        private int currentAdapterIndex = 0;

        // 上次更新时间
        private DateTime lastUpdateTime = DateTime.MinValue;

        public MainWindow()
        {
            InitializeComponent();
            InitializeWindowPosition();
            InitializeNetworkAdapters();
            InitializeTimer();
        }

        // 初始化窗口位置（右上角）
        private void InitializeWindowPosition()
        {
            Left = SystemParameters.WorkArea.Right - Width - 10;
            Top = SystemParameters.WorkArea.Top + 10;
        }

        // 初始化网络适配器列表
        private void InitializeNetworkAdapters()
        {
            try
            {
                networkAdapters.Clear();
                PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");

                foreach (string instance in category.GetInstanceNames())
                {
                    // 过滤掉环回接口和虚拟接口
                    if (!instance.Contains("Loopback") && !instance.Contains("VMware") && !instance.Contains("TAP"))
                    {
                        networkAdapters.Add(instance);
                    }
                }

                if (networkAdapters.Count > 0)
                {
                    SelectAdapter(0);
                }
                else
                {
                    AdapterText.Text = "适配器: 未找到";
                    StatusText.Text = "错误: 无可用适配器";
                }
            }
            catch (Exception ex)
            {
                StatusText.Text = "错误: " + ex.Message;
            }
        }

        // 初始化计时器
        private void InitializeTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        // 计时器事件处理
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (downloadCounter != null && uploadCounter != null)
            {
                try
                {
                    // 获取当前速度
                    float downloadSpeed = downloadCounter.NextValue() / 1024; // KB/s
                    float uploadSpeed = uploadCounter.NextValue() / 1024; // KB/s

                    // 更新UI
                    Dispatcher.Invoke(() =>
                    {
                        DownloadSpeedText.Text = $"{downloadSpeed:F2} KB/s";
                        UploadSpeedText.Text = $"{uploadSpeed:F2} KB/s";

                        // 更新时间
                        lastUpdateTime = DateTime.Now;
                        UpdateTimeText.Text = "更新: " + lastUpdateTime.ToString("HH:mm:ss");
                    });
                }
                catch (Exception ex)
                {
                    StatusText.Text = "错误: " + ex.Message;
                    timer.Stop();
                }
            }
        }

        // 选择网络适配器
        private void SelectAdapter(int index)
        {
            if (index >= 0 && index < networkAdapters.Count)
            {
                currentAdapterIndex = index;
                string adapterName = networkAdapters[index];
                InitializeCounters(adapterName);
                AdapterText.Text = "适配器: " + adapterName;
            }
        }

        // 初始化性能计数器
        private void InitializeCounters(string adapterName)
        {
            try
            {
                // 如果已存在计数器，先释放资源
                if (downloadCounter != null)
                {
                    downloadCounter.Dispose();
                }

                if (uploadCounter != null)
                {
                    uploadCounter.Dispose();
                }

                // 创建新的计数器
                downloadCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", adapterName);
                uploadCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", adapterName);

                // 初始化计数器值
                downloadCounter.NextValue();
                uploadCounter.NextValue();

                StatusText.Text = "运行中";
            }
            catch (Exception ex)
            {
                StatusText.Text = "错误: " + ex.Message;
            }
        }

        // 关闭按钮点击事件
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        // 设置按钮点击事件
        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 切换到下一个网络适配器
            if (networkAdapters.Count > 0)
            {
                currentAdapterIndex = (currentAdapterIndex + 1) % networkAdapters.Count;
                SelectAdapter(currentAdapterIndex);
            }
        }

        // 允许窗口拖动
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        // 窗口关闭时释放资源
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (timer != null && timer.IsEnabled)
            {
                timer.Stop();
            }

            if (downloadCounter != null)
            {
                downloadCounter.Dispose();
            }

            if (uploadCounter != null)
            {
                uploadCounter.Dispose();
            }
        }
    }
}